package org.jeecg.modules.extbpm.job;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.NativeTaskQuery;
import org.activiti.engine.task.Task;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bpm.dto.UserAgentDTO;
import org.jeecg.modules.bpm.service.ActivitiService;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecg.modules.extbpm.process.entity.ExtActBpmLog;
import org.jeecg.modules.extbpm.process.service.IExtActBpmLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
import java.util.List;

/**
 * 	用户代理任务
 * 
 * @author zhoujf
 */
@Slf4j
public class UserAgentJob implements Job {

	private static TaskService taskService;
	private static ActivitiService activitiService;
	private static IExtActBpmLogService extActBpmLogService;
	protected static RuntimeService runtimeService;
	static {
		taskService = SpringContextUtils.getBean(TaskService.class);
		activitiService = SpringContextUtils.getBean(ActivitiService.class);
		extActBpmLogService = SpringContextUtils.getBean(IExtActBpmLogService.class);
		runtimeService = SpringContextUtils.getBean(RuntimeService.class);
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info(String.format(" Jeecg-Boot 用户代理任务 UserAgentJob !  时间:" + DateUtils.getTimestamp()));
		try {
			//查询有代理设置的用户
			String currDateStr = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
			Date currDate = DateUtils.parseDate(currDateStr, "yyyy-MM-dd HH:mm:ss");
			List<UserAgentDTO> userAgentList = activitiService.getUserAgent(currDate);
			for(UserAgentDTO agent:userAgentList) {
				log.info("--------任务处理人："+agent.getUserName()+",代办人："+agent.getAgentUserName());
				taskDeal(agent);
			}
			
		} catch (Exception e) {
			log.error("Jeecg-Boot 用户代理任务 UserAgentJob 异常"+e.getMessage(),e);
		}
		
	}
	
	
	private void taskDeal(UserAgentDTO agent){
    	//1、查用户的待处理的任务
    	StringBuilder sb = new StringBuilder("");
		sb.append("select  * ").append("from (");
		//---update-begin-----autor:zhoujf------date:20190916-------for:未签收的任务不进行委派--------
		//sb.append("(select distinct RES.* ");
		//sb.append(" from ACT_RU_TASK RES inner join ACT_RU_IDENTITYLINK I on I.TASK_ID_ = RES.ID_ ");
		//sb.append("WHERE RES.ASSIGNEE_ is null and I.TYPE_ = 'candidate' ");
		//sb.append("	and ( I.USER_ID_ = #{userid}  or I.GROUP_ID_ IN ( select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{userid}  ) ");
		//sb.append(" ) ").append(" and RES.SUSPENSION_STATE_ = 1 ");
		//sb.append(") union ");
		//---update-end-----autor:zhoujf------date:20190916-------for:未签收的任务不进行委派--------
		sb.append("(select distinct RES.* ");
		sb.append(" from ACT_RU_TASK RES ");
		sb.append("WHERE RES.ASSIGNEE_ = #{userid} ");
		sb.append(" )) v ");
//		sb.append(" order by v.CREATE_TIME_ desc, v.PRIORITY_ desc ");
		
		NativeTaskQuery query = taskService.createNativeTaskQuery()
		.sql(sb.toString())
        .parameter("userid", agent.getUserName());
        List<Task> pretasks = query.list(); 
    	//2、任务委派给代理人
        for(Task task:pretasks){
        	log.info("-------------任务id:"+task.getId()+",taskName:"+task.getName());
        	try{
        		//---update-begin-----autor:zhoujf------date:20190916-------for:未签收的任务不进行委派--------
				//判断任务是否签收没有签收需要进行签收
				//if(oConvertUtils.isEmpty(task.getAssignee())) {
				//	taskService.claim(task.getId(), agent.getAgentUserName());
				//}
        		//---update-end-----autor:zhoujf------date:20190916-------for:未签收的任务不进行委派--------
        		taskService.delegateTask(task.getId(), agent.getAgentUserName());
    			String description = ""+task.getAssignee()==null?"系统":task.getAssignee()+" 委托任务【"+task.getName()+"】给 "+agent.getAgentUserName()+" 办理";
    			String processInstanceId = task.getProcessInstanceId();
    			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    	        
    			ExtActBpmLog bpmlog = new ExtActBpmLog();
    			if(processInstance!=null) {
    				bpmlog.setBusinessKey(processInstance.getBusinessKey());
    				bpmlog.setProcName(processInstance.getName());
    			}
//    			bpmlog.setOpStatus(opStatus);
    			bpmlog.setOpTime(new Date());
//    			bpmlog.setOpType(WorkFlowGlobals.BPM_OP_TYPE_1);
    			bpmlog.setOpUserId(WorkFlowGlobals.SYS_AGENT_JOB_OPUSER_ID);
    			bpmlog.setOpUserName("系统任务");
    			bpmlog.setProcInstId(processInstanceId);
    			bpmlog.setRemarks(description);
    			bpmlog.setTaskDefKey(task.getTaskDefinitionKey());
    			bpmlog.setTaskId(task.getId());
    			bpmlog.setTaskName(task.getName());
    			extActBpmLogService.save(bpmlog);
    			String msg = "用户"+task.getName()+"[任务,id:"+task.getId()+",taskName:"+task.getName()+"]委派给"+agent.getAgentUserName();
    			log.info(msg);
    		}catch(Exception e){
    			log.error("Jeecg-Boot 用户代理任务 UserAgentJob 异常"+e.getMessage(),e);
    		}
        }
    }
}
